const BaseService = require('./BaseService');
const userDao = require('../dao/UserDao');
const blockAuditDao = require('../dao/BlockAuditDao');
const { BlockAuditStatus, OrderStatus } = require('../constants/DbEnum');
const LambdaProxy = require('../utils/LambdaProxy');
const orderService = require('../service/OrderService');

/**
 * @author sven.wu@hrx.ai
 * @module service/BlockAudit
 */
class BlockAuditService extends BaseService {
  /**
   * constructor
   */
  constructor() {
    super(blockAuditDao);
  }

  /**
   * findBlockUsers
   * @return {Array}
   */
  findBlockUsers() {
    return this.dao.findBlockUsers();
  }

  /**
   * blockingUser
   * @param {String} username
   * @param {String} ids
   */
  async blockingUser(username, ids) {
    const promises = new Array();

    // mark blocking user
    promises.push(
      this.dao.update({ status: BlockAuditStatus.BLOCKING }, { where: { id: ids.split(',') } })
    );

    // notify user
    const user = await userDao.findOne({ username });
    const content =
      `<p>尊敬的用户 ${user.realName}</p>` +
      '<p>您因为超时确认订单，在未来48小时内您不能下单交易和现金提现.</p>' +
      '<p align="right">宽客团队</p>';
    promises.push(LambdaProxy.sendEmail('【宽客】限制交易提醒', user.email, content));

    // cancel orders
    promises.push(orderService.listMyOrders(username));
    const [, , orderResults] = await Promise.all(promises);
    for (const order of orderResults) {
      if (order.status == OrderStatus.PENDING) {
        console.info(`cancel order#${order.id}, since blocking user`);
        try {
          await orderService.cancelOrder(username, order.id);
        } catch (e) {
          console.error('cancel order failed', e);
        }
      }
    }
  }
}

module.exports = new BlockAuditService();
